package cn.znzz.cjm.global;

import cn.znzz.cjm.util.AjaxResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//全局异常处理
@RestControllerAdvice //可以在controller执行前，后做一些事情
public class GlobalExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handler(RuntimeException r){
        return AjaxResult.me().setSuccess(false).setMessage(r.getMessage()+"出错啦！");
    }

    //303校验参数异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handler(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        List<FieldError> fieldErrors = result.getFieldErrors();
        HashMap<String, Object> map = new HashMap<>();
        fieldErrors.stream().forEach((FieldError a)->{
            map.put(a.getField(),a.getDefaultMessage());
        });
        return AjaxResult.me().setSuccess(false).setMessage(map.toString()).setCode(HttpStatus.BAD_REQUEST.value());
    }
}
